package string;

/**
 * 替换字符串的空格为 20%
 */
public class ReplaceBlank {


  public String relpace(String str) {

    if (str == null || str.length() <= 0) {
      System.out.println("输入的字符串不合法");
    }

    int length = 0;
    for (int i = 0; i < str.length(); i++) {
      if (str.charAt(i) == ' ') {
        length++;
      }
    }
    StringBuilder sb = new StringBuilder();
    sb.setLength(str.length() + length * 2);

    int index = 0;
    int newIndex = 0;
    for (; index < str.length(); index++) {
      if (str.charAt(index) == ' ') {
        sb.setCharAt(newIndex++, '2');
        sb.setCharAt(newIndex++, '0');
        sb.setCharAt(newIndex++, '%');
      } else {
        sb.setCharAt(newIndex++, str.charAt(index));
      }
    }

    return sb.toString();

  }


  public static void main(String args[]) {
    ReplaceBlank replaceBlank = new ReplaceBlank();
    String str = "we are happy";
    String result = replaceBlank.relpace(str);
    System.out.println(result);
  }
}
